package cool.taomu.toolkit.groovy

import com.google.inject.Inject
import cool.taomu.toolkit.Context
import groovy.lang.Binding
import groovy.lang.GroovyShell
import java.io.InputStream
import java.io.SequenceInputStream
import java.util.Map
import java.util.Vector
import org.apache.commons.io.IOUtils
import org.codehaus.groovy.jsr223.GroovyScriptEngineImpl
import org.codehaus.groovy.runtime.InvokerHelper

class GroovyScript implements IScript {

    @Inject
    Context context

    override execute(Vector<InputStream> inputs, Map<String, Object> binds, String methodName, Object ... args) {
        try(var input = new SequenceInputStream(inputs.elements)) {
            return this.execute(IOUtils.toString(input, "UTF-8"), binds, methodName, args);
        }
    }

    override execute(String stext, Map<String, Object> binds, String methodName, Object ... args) {
        val Binding binding = new Binding();
        binding.setProperty("context", context)
        if (binds !== null) {
            binds.forEach [ k, v |
                binding.setProperty(k, v);
            ]
        }
        var shell = new GroovyShell(GroovyScriptEngineImpl.getClassLoader());
        var script = shell.parse(stext);
        var inv = InvokerHelper.createScript(script.getClass(), binding)
        return inv.invokeMethod(methodName, args);
    }

}
